package com.zyh.kafka.day01;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;

public class KafkaConsumerTest1 {
    public static void main(String[] args) {
        //1 提供消费者配置
        Properties consumerConfigs = new Properties();
        //a 链接kafka集群
        consumerConfigs.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"kafka24:9092");
        //b 配置key反序列化方式
        consumerConfigs.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //c 配置value反序列化方式
        consumerConfigs.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        //d 配置消费者组
        consumerConfigs.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"g1");
        //e 设置消费分区策略-3种
        //  默认区间策略
        //  轮询策略
        consumerConfigs.setProperty(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, RoundRobinAssignor.class.getName());
        //  黏着策略
        //  consumerConfigs.setProperty(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG,StickyAssignor.class.getName());
        //2。创建消费者对象
        KafkaConsumer<String,String> kafkaConsumer = new KafkaConsumer<>(consumerConfigs);

        //3。调用消费者的消费方法，需要订阅主题
        kafkaConsumer.subscribe(Arrays.asList("topic-a"));
        boolean boo = true;
        try {
            while (boo) {
                ConsumerRecords<String, String> poll = kafkaConsumer.poll(1000);
                for (ConsumerRecord<String, String> record : poll) {
                    String key = record.key();
                    String value = record.value();

                    String topic = record.topic();//所在主题
                    int partition = record.partition();//所在分区
                    long offset = record.offset();//下标
                    System.out.println("key ="+ key + ",value =" + value+ ",topic =" + topic + ",partition =" + partition + ",offset =" + offset);
                }
            }
        } catch (Exception e) {
            boo = false;
        } finally {
            //4。释放资源
            kafkaConsumer.close();
        }

    }
}
